package com.tanchengjin.admin.controller;

import com.github.pagehelper.PageHelper;
import com.tanchengjin.admin.model.dao.UserMapper;
import com.tanchengjin.admin.exception.ApplicationException;
import com.tanchengjin.admin.model.pojo.User;
import com.tanchengjin.admin.model.vo.UserVO;
import com.tanchengjin.admin.utils.LayuiAdminServerResponse;
import com.tanchengjin.admin.utils.ServerResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tanchengjin
 */
@Controller
@RequestMapping("${app.admin.prefix}/userManager")
public class UserManagerController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/userList", method = {RequestMethod.GET})
    @ResponseBody
    public LayuiAdminServerResponse index(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit) {
        PageHelper.startPage(page, limit);
        List<User> userList = userMapper.getAll();
        ArrayList<UserVO> userVOS = new ArrayList<>();
        userList.stream().forEach(e -> {
            UserVO userVO = this.buildUserVO(e);
            userVOS.add(userVO);
        });
        return LayuiAdminServerResponse.responseWithSuccess(userVOS, String.valueOf(userMapper.count()));
    }

    @RequestMapping(value = "/index", method = {RequestMethod.GET})
    public String indexView() {
        return "/admin/user/index";
    }

    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create() {
        return "/admin/user/add";
    }

    @RequestMapping(value = "", method = {RequestMethod.POST})
    @ResponseBody
    public String store() {
        return "";
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public ServerResponse<User> show(@PathVariable long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return ServerResponse.responseWithSuccess(user);
    }

    @RequestMapping(value = "/{id}/edit", method = {RequestMethod.GET})
    public String edit(Model view, @PathVariable(value = "id") long id) {
        User user = userMapper.selectByPrimaryKey(id);
        view.addAttribute("user", this.buildUserVO(user));
        return "/admin/user/edit";
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.PUT})
    @ResponseBody
    public ServerResponse update(@Validated UserVO userVO, @PathVariable("id") long id) {
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        user.setName(userVO.getUsername());


        //如果更新的是当前用户则不更新name
        User user1 = userMapper.selectByPrimaryKey(id);
        if (user1.getUsername().equals(user.getUsername())) {
            user.setName(null);
        } else {
            //判断用户名是否存在
            if (user.getUsername() != null) {
                User byUsername = userMapper.findByUsername(user.getUsername());
                if (byUsername != null) {
                    throw new ApplicationException("用户名已存在");
                }
            }
        }

        user.setId(id);
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailure(0, "更新失败，请重试", null);
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseBody
    public ServerResponse destroy(@PathVariable(value = "id") long id) {
        int i = userMapper.deleteByPrimaryKey(id);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailure(0, "删除失败请重试", null);
        }
    }

    private UserVO buildUserVO(User e) {
        UserVO userVO = new UserVO();
        userVO.setId(e.getId());
        userVO.setUsername(e.getUsername());
        userVO.setEmail(e.getEmail());
        userVO.setAvatarUrl("");
        userVO.setCreated_at(e.getCreatedAt());
        userVO.setIp("");
        userVO.setPhone(e.getPhone());
        userVO.setStatus(e.getStatus());
        userVO.setUpdated_at(e.getUpdatedAt());
        return userVO;
    }
}
